package com.xjh.utils.beanutils.internal.convertors;

import com.xjh.utils.beanutils.BeanCopyConvertor;
import com.xjh.utils.beanutils.BeanCopyUtils;

import java.lang.reflect.Array;

/**
 * Object数组转换器
 *
 * @company 湖南省安第斯信息科技有限公司, 版权所有
 * @author kevin
 * @date 2021/3/10
 */
@SuppressWarnings("rawtypes")
public class ObjectArrayConvertor implements BeanCopyConvertor {

	private Class<?> methodTargetType;
	
	private Class<?> methodSourceType;
	
	private Class<?> propertyOptionClass;
	
	
	public ObjectArrayConvertor( Class<?> methodSourceType, Class<?> methodTargetType, Class<?> propertyOptionClass) {
		this.methodSourceType = methodSourceType;
		this.methodTargetType = methodTargetType;
		this.propertyOptionClass = propertyOptionClass;
	}

	@Override
	public Object convertTo(Object object) {
		if( !object.getClass().isArray() )
			return null;
		if( !methodSourceType.equals(object.getClass().getComponentType()))
			return null;
		int length = Array.getLength(object);
		Object[] retObject = (Object[]) Array.newInstance(methodTargetType, length );
		for( int i =0; i<length; i++ ) {
			retObject[i] = BeanCopyUtils.copyBean(Array.get(object, i), methodTargetType, propertyOptionClass);
		}
		return retObject;
	}

}
